package com.sugou.services.input.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sugou.model.datas.Commodity;
import com.sugou.model.datas.Merchants;
import com.sugou.model.datas.ResidentialAreas;
import com.sugou.model.datas.ServerRelation;
import com.sugou.model.datas.embeddable.Point;
import com.sugou.services.input.InputService;
import com.sugou.services.support.BaseService;

@Service("inputService")
public class InputServiceImpl<E extends Serializable> extends BaseService<E> implements InputService<E> {
	private static final long serialVersionUID = 4971396125232571883L;
	
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED,noRollbackFor=Throwable.class)
	public Number saveMer(Merchants merchants,List<String> ras,List<Map<String, String>> comm ){
		this.save((E) merchants);
		for (String str : ras) {
			ResidentialAreas ra=(ResidentialAreas) this.getDao().getEntity("from ResidentialAreas where name=?", str);
			if(ra==null){
				ra=new ResidentialAreas();
				ra.setName(str);
				ra.setPoint(new Point(0,0));
				this.save((E) ra);
				ServerRelation sr=new ServerRelation();
				sr.setMerchants(merchants);
				sr.setResidentialAreas(ra);
				this.save((E) sr);
			}else{
				ServerRelation sr=(ServerRelation) this.getDao().getEntity("from ServerRelation where merchants=? and residentialAreas=?", merchants,ra);
				if(sr!=null){
					continue;
				}
				sr=new ServerRelation();
				sr.setMerchants(merchants);
				sr.setResidentialAreas(ra);
				this.save((E) sr);
			}
		}
		
		for (Map<String, String> map : comm) {
			Commodity commodity=new Commodity();
			commodity.setName(map.get("name"));
			commodity.setPrice(Double.valueOf(map.get("price")));
			commodity.setMerchants(merchants);
			this.save((E) commodity);
		}
		
		return 1;
	}
}
